﻿using System;
using System.Data.Services;
using System.Data.Services.Providers;
using umbraco.DataServices.Linq;

namespace umbraco.DataServices
{
    public abstract class ServiceBase : DataService<UmbracoContext>, IServiceProvider {

        private ServiceMetadata _metaData;
        private ServiceQueryProvider _queryProvider;
        private readonly UmbracoContextFactory _factory;

        protected ServiceBase() {
            _factory = UmbracoContextFactory.Instance;
        }

        public ServiceMetadata CreateMetadata() {
             if (_metaData == null)
                 _metaData = new ServiceMetadata("umbraco", "umbraco", _factory.PropertySignatures);
             return _metaData;
        }

        public ServiceQueryProvider CreateQueryProvider() {
            if (_queryProvider == null)
                _queryProvider = new ServiceQueryProvider(CreateMetadata(), CreateDataSource());
            return _queryProvider;
        }

        public object GetService(Type serviceType) {
            if (serviceType == typeof(IDataServiceMetadataProvider))
                return CreateMetadata();
            if (serviceType == typeof(IDataServiceQueryProvider))
                return CreateQueryProvider();
            return null; 
        }

        protected override UmbracoContext CreateDataSource() {
            return _factory.CreateContext();
        }
    }
}
